<script setup lang="ts">
  import { ArrowDown } from '@element-plus/icons-vue'
  import {
    useAutoCheckEndOrderService,
    useReceiveOrderStrategyService,
    useAutoCheckCancelOrderService,
    useEnableUpdateSparePriceService,
  } from './services'
  import { ref, watch } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import HButton from '@/components/common/button/HButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import {
    updateOrderWithdrawHandlingFee,
    updateWithdrawEmpRoot,
    updateSelectFeeEmpRoot,
  } from '@/api/network'
  import autoFixedDicimal from '@/utils/money'

  const props = defineProps({
    networkIds: {
      type: Array<string>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  // 工单id集合
  const ids = ref<Array<string>>([])
  // 使用批量更新允许更改备件价格策略服务
  const { isEnableUpdateSparePrice, enableUpdateSparePriceLoading, enableUpdateSparePriceFn } =
    useEnableUpdateSparePriceService(ids)

  // 自动批量更新允许更改备件价格策略
  const enableUpdateSparePriceStrategy = ref({
    modalVisible: false, // 弹窗状态
    onClose: (done?: () => void) => {
      // 弹窗关闭事件
      if (!enableUpdateSparePriceLoading.value) {
        enableUpdateSparePriceStrategy.value.modalVisible = false
        done && done()
      }
    },
    onSave: () => {
      ElMessageBox({
        type: 'warning',
        title: '提示',
        message: `是否修改选中服务区域的是否允许更改备件价格策略为：“${
          isEnableUpdateSparePrice.value ? '允许修改' : '禁止修改'
        }”？`,
        showCancelButton: true,
        closeOnClickModal: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '加载中...'
            // 弹窗保存事件
            const res = await enableUpdateSparePriceFn()
            ElMessage({
              type: res.success ? 'success' : 'error',
              message: res.message,
            })
            if (!enableUpdateSparePriceLoading.value) {
              instance.confirmButtonLoading = false
              instance.confirmButtonText = '确定'
              done()
              enableUpdateSparePriceStrategy.value.modalVisible = false
            }
            emits('update')
          } else {
            done()
          }
        },
      })
    },
  })

  // 使用自动审核结单策略服务
  const { autoCheckEndOrder, autoCheckEndOrderLoading, autoCheckEndOrderFn } =
    useAutoCheckEndOrderService(ids)

  // 自动审核结单策略
  const autoCheckEndOrderStrategy = ref({
    modalVisible: false, // 弹窗状态
    onClose: (done?: () => void) => {
      // 弹窗关闭事件
      if (!autoCheckEndOrderLoading.value) {
        autoCheckEndOrderStrategy.value.modalVisible = false
        done && done()
      }
    },
    onSave: () => {
      ElMessageBox({
        type: 'warning',
        title: '提示',
        message: `确认修改选中服务区域的自动审核结单策略为：“${
          autoCheckEndOrder.value ? '自动审核' : '人工审核'
        }”？`,
        showCancelButton: true,
        closeOnClickModal: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '加载中...'
            // 弹窗保存事件
            const res = await autoCheckEndOrderFn()
            ElMessage({
              type: res.success ? 'success' : 'error',
              message: res.message,
            })
            if (!autoCheckEndOrderLoading.value) {
              instance.confirmButtonLoading = false
              instance.confirmButtonText = '确定'
              done()
              autoCheckEndOrderStrategy.value.modalVisible = false
              emits('update')
            }
          } else {
            done()
          }
        },
      })
    },
  })

  // 使用自动审核取消工单策略服务
  const { autoCheckCancelOrder, autoCheckCancelOrderLoading, autoCheckCancelOrderFn } =
    useAutoCheckCancelOrderService(ids)

  // 自动审核取消工单策略
  const autoCheckCancelOrderStrategy = ref({
    modalVisible: false, // 弹窗状态
    onClose: (done?: () => void) => {
      // 弹窗关闭事件
      if (!autoCheckCancelOrderLoading.value) {
        autoCheckCancelOrderStrategy.value.modalVisible = false
        done && done()
      }
    },
    onSave: () => {
      ElMessageBox({
        type: 'warning',
        title: '提示',
        message: `确认修改选中服务区域的自动审核取消工单策略为：“${
          autoCheckCancelOrder.value ? '自动审核' : '人工审核'
        }”？`,
        showCancelButton: true,
        closeOnClickModal: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '加载中...'
            // 弹窗保存事件
            const res = await autoCheckCancelOrderFn()
            ElMessage({
              type: res.success ? 'success' : 'error',
              message: res.message,
            })
            if (!autoCheckCancelOrderLoading.value) {
              instance.confirmButtonLoading = false
              instance.confirmButtonText = '确定'
              done()
              autoCheckCancelOrderStrategy.value.modalVisible = false
              emits('update')
            }
          } else {
            done()
          }
        },
      })
    },
  })

  // 使用接单策略服务
  const { autoSureReceiveOrder, updateAutoSureReceiveOrderLoading, updateAutoSureReceiveOrderFn } =
    useReceiveOrderStrategyService(ids)

  // 接单策略
  const receiveOrderStrategy = ref({
    modalVisible: false, // 弹窗状态
    onClose: (done?: () => void) => {
      // 弹窗关闭事件
      if (!updateAutoSureReceiveOrderLoading.value) {
        receiveOrderStrategy.value.modalVisible = false
        done && done()
      }
    },
    onSave: () => {
      ElMessageBox({
        type: 'warning',
        title: '提示',
        message: `确认修改选中服务区域的接单策略为：“${
          autoSureReceiveOrder.value ? '自动接单' : '手动确认'
        }”？`,
        showCancelButton: true,
        closeOnClickModal: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '加载中...'
            // 弹窗保存事件
            const res = await updateAutoSureReceiveOrderFn()
            ElMessage({
              type: res.success ? 'success' : 'error',
              message: res.message,
            })
            if (!updateAutoSureReceiveOrderLoading.value) {
              instance.confirmButtonLoading = false
              instance.confirmButtonText = '确定'
              done()
              receiveOrderStrategy.value.modalVisible = false
              emits('update')
            }
          } else {
            done()
          }
        },
      })
    },
  })
  // 手续费策略修改
  const feeDialog = ref(false)
  const handlingFeeVo = ref({
    handingFeeFixedOrder: 0, //每单固定手续费：当withdrawHandlingFeeStrategy=2时生效
    handingFeeProportion: 0, //手续费比例，单位为%，当withdrawHandlingFeeStrategy=1时生效
    networkIds: [], //服务商ID
    withdrawHandlingFeeStrategy: 1, //提现手续费策略：1-按比例收取(按提现总金额计算)，2-每间固定(按每单总金额计算),示例值(1)
  })
  const onNetworkFee = () => {
    feeDialog.value = true
  }
  const loadingFee = ref(false)
  const onSaveFee = async () => {
    handlingFeeVo.value.networkIds = ids.value
    loadingFee.value = true
    await updateOrderWithdrawHandlingFee(handlingFeeVo.value).then((res) => {
      loadingFee.value = false
      if (res.data.success) {
        handlingFeeVo.value.withdrawHandlingFeeStrategy = 1
        handlingFeeVo.value.handingFeeFixedOrder = 0
        handlingFeeVo.value.handingFeeProportion = 0
        handlingFeeVo.value.networkIds = []
        feeDialog.value = false
        emits('update')
      }
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: res.data.success ? 'success' : 'error',
          duration: 4000,
        })
    })
  }
  watch(
    () => props.networkIds,
    (value) => {
      ids.value = value
    },
  )

  /**
   * allow - 是否允许：false-不允许，true-允许
   * empType = 人员类型：1-团队负责人，2-工程师
   * networkIds - 服务商id集合
   * rule - 提现规则
   * allowManagerHelpWithdraw - 是否允许管理员代提现：false-不允许，true-允许
   */
  const withdrawEmpRootVo = ref({
    allow: true,
    empType: [1, 2],
    networkIds: [],
    allowManagerHelpWithdraw: false,
  })
  const withdrawEmpShow = ref(false)
  const onSavewithdrawEmp = async () => {
    withdrawEmpRootVo.value.networkIds = ids.value
    loadingFee.value = true
    await updateWithdrawEmpRoot(withdrawEmpRootVo.value).then((res) => {
      loadingFee.value = false
      if (res.data.success) {
        withdrawEmpRootVo.value.allow = true
        withdrawEmpRootVo.value.empType = [1, 2]
        withdrawEmpRootVo.value.networkIds = []
        withdrawEmpShow.value = false
        emits('update')
      }
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: res.data.success ? 'success' : 'error',
          duration: 4000,
        })
    })
  }
  /**
 * allow	是否允许：false-不允许，true-允许,示例值(true)		true	
boolean
empType	人员类型：1-团队负责人，2-工程师,示例值([ 1, 2 ])		false	
array
integer
networkIds
 */
  const updateSelectFeeEmpVo = ref({
    allow: true,
    empType: [1, 2],
    networkIds: [],
  })
  const updateSelectFeeEmpShow = ref(false)
  const updateSelectFeeEmpSave = async () => {
    updateSelectFeeEmpVo.value.networkIds = ids.value
    loadingFee.value = true
    await updateSelectFeeEmpRoot(updateSelectFeeEmpVo.value).then((res) => {
      loadingFee.value = false
      if (res.data.success) {
        updateSelectFeeEmpVo.value.allow = true
        updateSelectFeeEmpVo.value.empType = [1, 2]
        updateSelectFeeEmpVo.value.networkIds = []
        updateSelectFeeEmpShow.value = false
        emits('update')
      }
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: res.data.success ? 'success' : 'error',
          duration: 4000,
        })
    })
  }
</script>

<template>
  <div>
    <el-dropdown trigger="click">
      <HButton :disabled="!props.networkIds || props.networkIds.length <= 0">
        <span>编辑策略</span>
        <el-icon style="margin-left: 5px">
          <ArrowDown />
        </el-icon>
      </HButton>

      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="receiveOrderStrategy.modalVisible = true"
            >接单策略</el-dropdown-item
          >
          <el-dropdown-item @click="onNetworkFee" :disabled="props.networkIds.length <= 0">
            提现手续费
          </el-dropdown-item>
          <el-dropdown-item
            @click="withdrawEmpShow = true"
            :disabled="props.networkIds.length <= 0"
          >
            提现权限
          </el-dropdown-item>
          <el-dropdown-item
            @click="updateSelectFeeEmpShow = true"
            :disabled="props.networkIds.length <= 0"
          >
            费用查看
          </el-dropdown-item>
          <el-dropdown-item @click="autoCheckCancelOrderStrategy.modalVisible = true"
            >取消工单</el-dropdown-item
          >
          <el-dropdown-item @click="autoCheckEndOrderStrategy.modalVisible = true"
            >结单审核</el-dropdown-item
          >
          <el-dropdown-item @click="enableUpdateSparePriceStrategy.modalVisible = true"
            >配件价格</el-dropdown-item
          >
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <HModal
      title="接单策略"
      v-model="receiveOrderStrategy.modalVisible"
      @close="receiveOrderStrategy.onClose"
      size="small"
    >
      <el-form v-loading="updateAutoSureReceiveOrderLoading">
        <el-form-item label="接单策略" style="margin: 0">
          <el-radio-group v-model="autoSureReceiveOrder">
            <el-radio :value="true">自动接单</el-radio>
            <el-radio :value="false">手动接单</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footerRight>
        <HButton
          type="primary"
          is-modal
          @click="receiveOrderStrategy.onSave()"
          :loading="updateAutoSureReceiveOrderLoading"
          >保存</HButton
        >
        <HButton
          is-modal
          :loading="updateAutoSureReceiveOrderLoading"
          @click="receiveOrderStrategy.onClose()"
          >取消
        </HButton>
      </template>
    </HModal>

    <HModal
      title="自动审核取消工单策略"
      v-model="autoCheckCancelOrderStrategy.modalVisible"
      @close="autoCheckCancelOrderStrategy.onClose"
      size="small"
    >
      <el-form v-loading="autoCheckCancelOrderLoading">
        <el-form-item label="取消工单" style="margin: 0">
          <el-radio-group v-model="autoCheckCancelOrder">
            <el-radio :value="false">人工审核</el-radio>
            <el-radio :value="true">自动审核</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footerRight>
        <HButton
          type="primary"
          is-modal
          @click="autoCheckCancelOrderStrategy.onSave()"
          :loading="autoCheckCancelOrderLoading"
          >保存</HButton
        >
        <HButton
          is-modal
          :loading="autoCheckCancelOrderLoading"
          @click="autoCheckCancelOrderStrategy.onClose()"
          >取消
        </HButton>
      </template>
    </HModal>

    <HModal
      title="自动审核结单策略"
      v-model="autoCheckEndOrderStrategy.modalVisible"
      @close="autoCheckEndOrderStrategy.onClose"
      size="small"
    >
      <el-form v-loading="autoCheckEndOrderLoading">
        <el-form-item label="结单审核" style="margin: 0">
          <el-radio-group v-model="autoCheckEndOrder">
            <el-radio :value="false">人工审核</el-radio>
            <el-radio :value="true">自动审核</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footerRight>
        <HButton
          type="primary"
          is-modal
          @click="autoCheckEndOrderStrategy.onSave()"
          :loading="autoCheckEndOrderLoading"
          >保存</HButton
        >
        <HButton
          is-modal
          :loading="autoCheckEndOrderLoading"
          @click="autoCheckEndOrderStrategy.onClose()"
          >取消</HButton
        >
      </template>
    </HModal>

    <HModal
      title="更新允许更改备件价格策略"
      v-model="enableUpdateSparePriceStrategy.modalVisible"
      @close="enableUpdateSparePriceStrategy.onClose"
      size="small"
    >
      <el-form v-loading="enableUpdateSparePriceLoading">
        <el-form-item label="配件价格" style="margin: 0">
          <el-radio-group v-model="isEnableUpdateSparePrice">
            <el-radio :value="true">允许修改</el-radio>
            <el-radio :value="false">禁止修改</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footerRight>
        <HButton
          type="primary"
          is-modal
          @click="enableUpdateSparePriceStrategy.onSave()"
          :loading="enableUpdateSparePriceLoading"
          >保存</HButton
        >
        <h-button
          is-modal
          :loading="enableUpdateSparePriceLoading"
          @click="enableUpdateSparePriceStrategy.onClose()"
          >取消</h-button
        >
      </template>
    </HModal>

    <HModal title="工单手续费" v-model="feeDialog" size="small">
      <el-form
        :model="handlingFeeVo"
        label-width="auto"
        label-position="right"
        v-loading="loadingFee"
        element-loading-text="加载中..."
        class="service_fee_form_content"
      >
        <!--提现手续费-->
        <el-form-item label="提现手续费策略" class="form_item">
          <el-radio-group v-model="handlingFeeVo.withdrawHandlingFeeStrategy">
            <el-radio :value="1">按比例收取</el-radio>
            <el-radio :value="2">每年固定</el-radio>
          </el-radio-group>
        </el-form-item>

        <!--手续费比例-->
        <el-form-item label="手续费比例(%)" class="form_item">
          <el-input
            v-model="handlingFeeVo.handingFeeProportion"
            :disabled="handlingFeeVo.withdrawHandlingFeeStrategy == 2"
            placeholder=""
            @input="
              handlingFeeVo.handingFeeProportion = autoFixedDicimal(
                handlingFeeVo.handingFeeProportion,
              )
            "
            @change="
              handlingFeeVo.handingFeeFixedOrder = Number(handlingFeeVo.handingFeeProportion)
            "
          >
          </el-input>
        </el-form-item>

        <!--每单固定手续费-->
        <el-form-item label="每单固定手续费">
          <el-input
            v-model="handlingFeeVo.handingFeeFixedOrder"
            :disabled="handlingFeeVo.withdrawHandlingFeeStrategy == 1"
            placeholder=""
            @input="
              handlingFeeVo.handingFeeFixedOrder = autoFixedDicimal(
                handlingFeeVo.handingFeeFixedOrder,
              )
            "
            @change="
              handlingFeeVo.handingFeeFixedOrder = Number(handlingFeeVo.handingFeeFixedOrder)
            "
          >
            <template #prepend> ￥ </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footerRight>
        <HButton is-modal type="primary" @click="onSaveFee">保存</HButton>
        <HButton is-modal @click="feeDialog = false">取消</HButton>
      </template>
    </HModal>

    <HModal title="提现权限策略" v-model="withdrawEmpShow" size="small">
      <el-form
        :model="handlingFeeVo"
        label-width="auto"
        label-position="right"
        v-loading="loadingFee"
        element-loading-text="加载中..."
        class="service_fee_form_content"
      >
        <el-form-item label="提现权限" class="form_item">
          <el-radio-group v-model="withdrawEmpRootVo.allow">
            <el-radio :value="true">允许提现</el-radio>
            <el-radio :value="false">不允许提现</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="人员类型" class="form_item">
          <el-checkbox-group v-model="withdrawEmpRootVo.empType">
            <el-checkbox :value="1">团队负责人</el-checkbox>
            <el-checkbox :value="2">工程师</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="提现规则" class="form_item">
          <el-checkbox v-model="withdrawEmpRootVo.allowManagerHelpWithdraw"
            >是否允许管理员代提现</el-checkbox
          >
        </el-form-item>
      </el-form>
      <template #footerRight>
        <HButton is-modal type="primary" @click="onSavewithdrawEmp">保存</HButton>
        <HButton is-modal @click="withdrawEmpShow = false">取消</HButton>
      </template>
    </HModal>

    <HModal title="费用查看策略" v-model="updateSelectFeeEmpShow" size="small">
      <el-form
        :model="handlingFeeVo"
        label-width="auto"
        label-position="right"
        v-loading="loadingFee"
        element-loading-text="加载中..."
        class="service_fee_form_content"
      >
        <el-form-item label="提现权限" class="form_item">
          <el-radio-group v-model="updateSelectFeeEmpVo.allow">
            <el-radio :value="true">允许查看</el-radio>
            <el-radio :value="false">不允许查看</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="人员类型" class="form_item">
          <el-checkbox-group v-model="updateSelectFeeEmpVo.empType">
            <el-checkbox :value="1">团队负责人</el-checkbox>
            <el-checkbox :value="2">工程师</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footerRight>
        <HButton is-modal type="primary" @click="updateSelectFeeEmpSave">保存</HButton>
        <HButton is-modal @click="updateSelectFeeEmpShow = false">取消</HButton>
      </template>
    </HModal>
  </div>
</template>

<style scoped lang="scss">
  .service_fee_form_content {
    .form_item {
      margin-bottom: 12px;
    }
  }
</style>
